public class PrintBinaryTree {
    private static class Node{
        public int value;
        public Node left;
        public Node right;

        public Node(int v){
            value = v;
        }
    }

    public static void printTree(Node head){
        System.out.println("Binary Tree:");
        printInorder(head, 0, "H", 17);
        System.out.println();
    }

    public static void printInorder(Node head, int height, String to, int len){
        if (head == null){
            return;
        }

        printInorder(head.right, height + 1, "v", len);
        String val = to + head.value + to;
        int lenM = val.length();
        int lenL = (len - lenM) / 2;
        int lenR = len - lenM - lenL;
        val = getSpace(lenL) + val + getSpace(lenR);
        System.out.println(getSpace(height * len) + val);//在要打印的前面增加空格，显得对齐
        printInorder(head.left, height + 1, "^", len);
    }

    public static String getSpace(int num){
        String space = "$";
        StringBuffer buf = new StringBuffer("");
        for (int i = 0; i < num; i++){
            buf.append(space);
        }
        return buf.toString();
    }

    public static void main(String[] args) {
        Node head = new Node(1);
        head.left = new Node(2);
        head.right = new Node(3);
        head.left.left = new Node(4);
        head.left.right = new Node(5);
        head.right.left = new Node(6);
        head.right.right = new Node(7);
        printTree(head);
    }
}
